package com.atguigu.gmall.realtime.util;


import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author lzc
 * @Date 2023/2/11 14:31
 */
@Slf4j
public class AtguiguUtil {
    private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    /**
     * 把 ms 值转成年月日
     * 格式: 2023-01-03
     *
     * @param ts
     * @return
     */
    public static String tsToDate(Long ts) {
        
        // 多线程: 有线程安全问题
        //return new SimpleDateFormat("yyyy-MM-dd").format(ts);
        
        return dateFormatter.format(LocalDateTime.ofInstant(new Date(ts).toInstant(), ZoneId.systemDefault()));
    }
    
    public static void main(String[] args) throws IOException, URISyntaxException {
        Set<String> set = mySplit("我是中国人");
        for (String kw : set) {
    
            System.out.println(kw);
        }
    }
    
    public static String findAppLastJobLastCk(String ckPath) {
        /*
        // 自动从状态恢复数据
        String lastJobLastCk = AtguiguUtil.findAppLastJobLastCk("hdfs://hadoop162:8020/gmall/" + ckAndJobName);
        
        if (lastJobLastCk != null) {
            System.out.println(lastJobLastCk);
            conf.setString("execution.savepoint.path", lastJobLastCk);
        }
         */
        
        try {
            System.setProperty("HADOOP_USER_NAME", "atguigu");
            Configuration hdfsConfig = new Configuration();
            hdfsConfig.set("fs.defaultFS", "hdfs://hadoop162:8020");
            FileSystem fs = FileSystem.get(hdfsConfig);
            
            // 所有的 job 目录
            FileStatus[] jobs = fs.listStatus(new Path(ckPath));
            // 找到最后一个 job
            Optional<FileStatus> op1 = Arrays.stream(jobs).max(Comparator.comparingLong(FileStatus::getModificationTime));
            if (op1.isPresent()) {
                Path path = op1.get().getPath();
                FileStatus[] cks = fs.listStatus(path);
                // 最后一个 job 的最后一个 checkpoint 目录
                Optional<FileStatus> op2 = Arrays.stream(cks).filter(x -> x.getPath().getName().startsWith("chk")).max(Comparator.comparingLong(FileStatus::getModificationTime));
                if (op2.isPresent()) {
                    FileStatus path2 = op2.get();
                    return path2.getPath().toString();
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("首次启动, 无法从 checkpoint 恢复状态数据...");
        }
        return null;
    }
    
    // TODO
    public static Set<String> mySplit(String kw) {
        if (kw == null) {
            return null;
        }
        Set<String> set = new HashSet<>();
        // 如果把字符串变成字符输入流 ?
        // 内存流:
        Reader reader = new StringReader(kw);
        IKSegmenter segmenter = new IKSegmenter(reader, true);
    
        try {
            Lexeme lexeme = segmenter.next();
            while (lexeme != null) {
                String keyword = lexeme.getLexemeText();
                // 存入到 set 集合中
                set.add(keyword);
                lexeme = segmenter.next();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    
        
        return set;
    }
    
    public static String tsToDateTime(long ts) {
        return dateTimeFormatter.format(LocalDateTime.ofInstant(new Date(ts).toInstant(), ZoneId.systemDefault()));
    }
    
    public static Long dateToTs(String date) throws ParseException {
        return new SimpleDateFormat("yyyy-MM-dd").parse(date).getTime();
    }
}
